package com.tarry.trade.counter.filter;

import com.google.common.collect.Sets;
import com.tarry.trade.counter.exception.BusinessException;
import com.tarry.trade.counter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;

@Component
@Slf4j
public class SessionCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Autowired
    private UserService userService;

    // 白名单
    private Set<String> whiteRootPaths = Sets.newHashSet("/login/userLogin", "/login/captcha");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 跨域
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) servletRequest).getMethod())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
        }

        // 白名单校验
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String path = httpServletRequest.getRequestURI();
        log.info("path:{}", path);
        if (whiteRootPaths.contains(path)) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            if (userService.accountExistInCache(httpServletRequest.getParameter("token"))){
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                httpServletRequest.setAttribute("msg", "登录信息过期，请重新登录~");
                httpServletRequest.getRequestDispatcher("/login/loginFail").forward(httpServletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
